package com.wechatnotice.wechatnotice.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * @author Admin
 */
@Component
@Slf4j
public class WxWorkSendUtil {

    /**
     * corpId、corpSecret问下企业微信管理后台,corpSecret应该是应用独立Secret
     */
    private final static String AGENT_ID="1000002";
    private final static String CORP_ID="wwe75fcfef80661c75";
    private final static String CORP_SECRET="aJJ7F4-H8ak8fU6R69Bwu_tLQvDLhcOMRaVb4-zagcU";

    /**
     * 获取token
     */
    private final static String URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CORP_ID+"&corpsecret="+CORP_SECRET;
    private static String ACCESS_TOKEN = "";

    public static String getToken() {
        String getResult = HttpUtil.get(URL);
        Map beanMap = JSONUtil.toBean(getResult, Map.class);
        if ("ok".equals(beanMap.get("errmsg"))){
            ACCESS_TOKEN = beanMap.get("access_token").toString();
        }
        return ACCESS_TOKEN;
    }

    /**
     * 创建POST BODY
     * @param touser 用户id
     * @param msgtype 消息类型
     * @param agent_id 应用id
     * @param contentKey 消息体类型
     * @param contentValue 消息文本
     * @return
     * {
     *         "touser" : "UserID1|UserID2|UserID3",
     *             "toparty" : "PartyID1|PartyID2",
     *             "totag" : "TagID1 | TagID2",
     *             "msgtype" : "text",
     *             "agentid" : 1,
     *             "text" : {
     *         "content" : "你的快递已到，请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>，聪明避开排队。"
     *         }
     *     }
     */
    private static Map<String,Object> createPostData(String touser, String msgtype, int agent_id, String contentKey, String contentValue) {
        Map<String, Object> postData = new HashMap<>(10);
        postData.put("touser",touser);
        postData.put("agentid",agent_id);
        postData.put("msgtype",msgtype);
        Map<String, Object> content = new HashMap<>(1);
        content.put(contentKey,contentValue);
        postData.put(msgtype,content);
        return postData;
    }

    /**
     * 手机号获取userid
     * @param phone  手机号
     * @return userid
     */
    private static String createPostByPhoneData(String phone) {
        Map<String,String> map=new HashMap<>(1);
        map.put("mobile",phone);
        return JSONUtil.parseObj(map).toString();
    }

    /**
     * 发送post请求
     * 形参:
     * urlString – 网址
     * paramMap – post表单数据
     * 返回值:
     * 返回数据
     * @return 请求返回
     */
    private static Map post(String url, String json) {
        String postResult = HttpUtil.post(url, json);
        return JSONUtil.toBean(postResult, Map.class);
    }

    /**
     * 发送文本消息
     * @param toUser 用户id
     * @param contentValue 文本
     */
    public static void sendTextMesg(String toUser, String contentValue) {
        String token = getToken();
        Map<String,Object> postData = createPostData(toUser, "text", 1000002, "content", contentValue);
        System.out.println("\n\n===================================================================================");
        log.info("获取到的token======>" + token);
        log.info("请求数据======>" + postData);
        String json = JSONUtil.parseObj(postData).toString();
        log.info("请求数据-json======>" + json);
        log.info("发送企业微信的响应数据======>" + post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+ACCESS_TOKEN,json));
    }


    public static void main(String[] args) {
//        sendTextMesg("yuhandong","将对象转换成 map对象 and hutool 将对象转换成json字符串");
//        String replacement = "-66-77".replaceAll("[~-]+", "~");
//        String replacement2 = "6~1000".replaceAll("[~-]+", "sss");
//        System.out.println(replacement);
//        System.out.println(replacement2);


        getToken();
        String json = createPostByPhoneData("13788393114");
        Map post = post("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + ACCESS_TOKEN, json);
        System.out.println(post);
        if (ObjectUtil.isNotEmpty(post.get("userid"))){
            sendTextMesg(post.get("userid").toString(),"将对象转换成 map对象 and hutool 将对象转换成json字符串\n"+"❤"+System.currentTimeMillis());
        }else {
            System.out.println(post);
        }
    }


}
